package com.vframework.system.login.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vframework.system.permission.entity.SysPermission;
import com.vframework.system.permission.mapper.SysPermissionMapper;
import com.vframework.system.user.entity.SysUser;
import com.vframework.system.user.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * spring security登陆处理<br>
 *
 * @author shanzhitong
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	private SysUserService userService;
	@Autowired
	private SysPermissionMapper permissionMapper;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		SysUser sysUser = userService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username));
		if (sysUser == null) {
			throw new AuthenticationCredentialsNotFoundException("用户名不存在");
		} else if (sysUser.getStatus() == SysUser.UserStatusEnum.LOCKED.getCode()) {
			throw new LockedException("用户被锁定,请联系管理员");
		} else if (sysUser.getStatus() == SysUser.UserStatusEnum.DISABLED.getCode()) {
			throw new DisabledException("用户已作废");
		}
        List<SysPermission> permissions;
        if ("admin".equals(username)) {
			permissions = permissionMapper.selectList(new QueryWrapper<>());
			if (permissions == null || permissions.size() == 0) {
				SysPermission permission = new SysPermission();
				// 超级管理用户添加自动“自动同步权限”功能的权限
				permission.setPermission("sys:permission:sync");
				permissions.add(permission);
			}
        } else {
			permissions = permissionMapper.getListByUserId(sysUser.getId());
        }
		sysUser.setPermissions(permissions);
		return sysUser;
	}

}
